/*
 * Copyright 2018 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.panwenliang2008.eatwhat.ui.selectoption

import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import com.afollestad.materialdialogs.MaterialDialog
import com.panwenliang2008.eatwhat.R
import com.panwenliang2008.eatwhat.data.entity.Food
import com.panwenliang2008.eatwhat.databinding.ItemSelectOptionBinding

/**
 * Adapter for the [RecyclerView] in [SelectOptionFragment].
 */
class SelectOptionAdapter(
    private val clickCallback: ((Food) -> Unit)?
) : ListAdapter<Food, SelectOptionAdapter.FoodViewHolder>(
    FoodDiffCallback()
) {

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): FoodViewHolder {
        return FoodViewHolder(
            ItemSelectOptionBinding.inflate(
                LayoutInflater.from(parent.context), parent, false
            ),
            clickCallback
        )
    }

    override fun onBindViewHolder(holder: FoodViewHolder, position: Int) {
        holder.bind(getItem(position))
    }

    class FoodViewHolder(
        private val binding: ItemSelectOptionBinding,
        clickCallback: ((Food) -> Unit)?
    ) : RecyclerView.ViewHolder(binding.root) {
        init {
            binding.setClickListener {
                MaterialDialog(it.context).show {
                    message(R.string.selectoption_message_001)
                    positiveButton(R.string.selectoption_message_002) {
                        binding.food?.let { food ->
                            clickCallback?.invoke(food)
                        }
                    }
                    negativeButton(R.string.selectoption_message_003)
                }
            }
        }

        fun bind(item: Food) {
            binding.apply {
                food = item
                executePendingBindings()
            }
        }
    }
}

private class FoodDiffCallback : DiffUtil.ItemCallback<Food>() {

    override fun areItemsTheSame(oldItem: Food, newItem: Food): Boolean {
        return oldItem.foodId == newItem.foodId
    }

    override fun areContentsTheSame(oldItem: Food, newItem: Food): Boolean {
        return oldItem == newItem
    }
}